package service

import (
	"context"
	"go-admin/server/internal/domain"
	"go-admin/server/internal/repository"
)

var (
	ErrRoleDuplicate = repository.ErrRoleDuplicate
)

type RbacService interface {
	CreateRole(ctx context.Context, ard domain.RoleData) error
	UpdateRole(ctx context.Context, erd domain.RoleData) error
	DelRole(ctx context.Context, roleId int32) error
	RoleLst(ctx context.Context) ([]domain.RoleData, error)

	AuthDataLst(ctx context.Context, roleId int32) ([]domain.RoleMenuData, error)
	AuthOperation(ctx context.Context, data domain.AuthData) error
	GetAdminRoleData(ctx context.Context) ([]domain.CreateAdminSelectRoleLst, error)
}

type rbacService struct {
	repo repository.RbacRepository
}

func NewRbacService(repo repository.RbacRepository) RbacService {
	return &rbacService{
		repo: repo,
	}
}

func (r *rbacService) CreateRole(ctx context.Context, ard domain.RoleData) error {
	err := r.repo.CreateRole(ctx, ard)
	if err == repository.ErrRoleDuplicate {
		return ErrRoleDuplicate
	}
	return err
}

func (r *rbacService) UpdateRole(ctx context.Context, erd domain.RoleData) error {
	return r.repo.UpdateRole(ctx, erd)
}

func (r *rbacService) DelRole(ctx context.Context, roleId int32) error {
	return r.repo.DelRole(ctx, roleId)
}

func (r *rbacService) RoleLst(ctx context.Context) ([]domain.RoleData, error) {
	lst, err := r.repo.RoleLst(ctx)
	if err != nil {
		return []domain.RoleData{}, err
	}
	return lst, nil
}

func (r *rbacService) AuthDataLst(ctx context.Context, roleId int32) ([]domain.RoleMenuData, error) {
	data, err := r.repo.GetAuthData(ctx, roleId)
	if err != nil {
		return []domain.RoleMenuData{}, err
	}
	return data, nil
}

func (r *rbacService) AuthOperation(ctx context.Context, data domain.AuthData) error {
	return r.repo.AuthOperation(ctx, data)
}

func (r *rbacService) GetAdminRoleData(ctx context.Context) ([]domain.CreateAdminSelectRoleLst, error) {
	data, err := r.repo.GetAdminRoleData(ctx)
	return data, err
}
